package com.study.csv;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
/**
 * <p>添加类描述</p>
 *
 * @author chentao
 * @version v 0.1 2024/6/17 17:00
 */
public class CSV4 {
    public static void main(String[] args) throws IOException {
        String v1 = "name1:v1";
        String v2 = "name2:v2";
        String v3 = "name3:v3";
        File file = new File("C:\\test\\test44.csv");
        FileOutputStream out = new FileOutputStream(file);

        // 判断是否存在 v1 和 v2
        boolean hasV1 = v1 != null && !v1.isEmpty();
        boolean hasV2 = v2 != null && !v2.isEmpty();
        boolean hasV3 = v3 != null && !v3.isEmpty();

        // 调整表头
        StringBuilder header = new StringBuilder("\t姓名,\t年级");
        if (hasV1) {
            header.append(",\t").append(v1.split(":")[1]);
        }
        if (hasV2) {
            header.append(",\t").append(v2.split(":")[1]);
        }
        if (hasV3) {
            header.append(",\t").append(v3.split(":")[1]);
        }
        header.append("\r\n");

        // 写入表头到文件
        out.write(header.toString().getBytes("GBK"));

        // 数据行的模式
        String rowPattern = "\t{0},\t{1}";
        if (hasV1) {
            rowPattern += ",\t{2}";
        }
        if (hasV2) {
            rowPattern += ",\t{3}";
        }
        if (hasV3) {
            rowPattern += ",\t{4}";
        }
        rowPattern += "\r\n";

        // 准备数据行
        ArrayList<Person> peoples = new ArrayList<>();
        Person person = new Person();
        person.setName("1");
        person.setAge("1");
        person.setName1("setName1");
        person.setName2("setName2");
        person.setName3("setName2");
        peoples.add(person);

        for (Person people : peoples) {
            ArrayList<Object> rowData = new ArrayList<>();
            rowData.add(people.getName());
            rowData.add(people.getAge());
            if (hasV1) {
                rowData.add(people.getName1());
            }
            if (hasV2) {
                rowData.add(people.getName2());
            }
            if (hasV3) {
                rowData.add(people.getName3());
            }
            out.write(MessageFormat.format(rowPattern, rowData.toArray()).getBytes("GBK"));
        }

        out.close();
    }
}
